﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using RayD.Core;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.IO;
using System.Linq;

namespace RayD.App.Setup
{
    /// <summary>
    /// Swagger 启动服务
    /// </summary>
    public static class SwaggerSetup
    {
        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));


            /*
             * 如果不想显示某些接口，直接在controller 上，或者action 上，增加特性 [ApiExplorerSettings(IgnoreApi = true)]
            */
            var basePath = AppContext.BaseDirectory;

            services.AddSwaggerGen(c =>
            {
                //生成文档时，类名相同命名空间不同会报错Conflicting schemaIds; 配置类名显示为完全限定名
                c.CustomSchemaIds(x => x.FullName);
                //遍历出全部的版本，做文档信息展示
                typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{AppSettings.ProjectName.CName}接口文档",
                        Description = $"{AppSettings.ProjectName.EName} API " + version,
                        Contact = new OpenApiContact { Name = $"API", Email = "244632399@qq.com", Url = new Uri("http://www.rayd.plus/vueadmin") },
                        License = new OpenApiLicense { Name = $"API", Url = new Uri("http://www.rayd.plus/vueadmin") }
                    });
                    // 按相对路径排序
                    c.OrderActionsBy(o => o.RelativePath);
                });

                #region 将注释添加在SwaggerUI上
                try
                {
                    var xmlPath = Path.Combine(basePath, "RayD.WebApi.xml");//这个就是刚刚配置的xml文件名
                    c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false，这个是controller的注释，记得修改 
                    var xmlModelPath = Path.Combine(basePath, "RayD.Entites.xml");//这个就是Model层的xml文件名
                    c.IncludeXmlComments(xmlModelPath);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                #endregion

                #region Token绑定到ConfigureServices
                // 开启加权小锁
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                // 在header中添加token，传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();

                // Jwt Bearer 认证，必须是 oauth2
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });
                #endregion
            });
        }
    }
}
